﻿using System;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Context;
using Rio.Framework.Pages.Helpers;
using Rio.Framework.Pages.Helpers.DragDrop;
using Rio.Framework.Pages.Helpers.Utils;
using Rio.Framework.Pages.Manager;
using Rio.Framework.Pages.UserControls;
using Rio.Framework.WCFService;
using Rio.Framework.WCFService.RioWcfServices;
using Telerik.Windows;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using Rio.Framework.Pages.AppCode.Enums;
using System.IO;
using Telerik.Windows.Controls.DragDrop;
using Folder = NetBay.Core.BusinessEntities.Folder;

namespace Rio.Framework.Pages.Viewer
{

    public partial class ListViewer
    {
        #region Attibuts
        private List<NetBay.Core.BusinessEntities.Document> _selectedSearchDocuments;

        public static readonly DependencyProperty ImagesProperty =
                DependencyProperty.Register("Images", typeof(IList), typeof(ListViewer), null);
        #endregion

        #region Properties

        public override bool ScanImportIsEnabled
        {
            get
            {
                return base.ScanImportIsEnabled;
            }
            set
            {
                base.ScanImportIsEnabled = value;
                if (DocumentToolbar != null)
                {
                    DocumentToolbar.ScanImportIsEnabled = value;
                    DocumentToolbar.ManageToolbar();
                }
            }
        }

        /// <summary>
        /// Gets or sets the images.
        /// </summary>
        /// <value>The images.</value>
        public IList Images
        {
            get { return (IList)GetValue(ImagesProperty); }
            set { SetValue(ImagesProperty, value); }
        }

        /// <summary>
        /// Gets or sets the index of the selected image.
        /// </summary>
        /// <value>The index of the selected image.</value>
        public int SelectedImageIndex
        {
            get
            {
                return Images.IndexOf(GridViewDoc.SelectedItem);
            }

            set
            {
                GridViewDoc.SelectedItems.Clear();
                try
                {
                    if (Images != null && value < Images.Count && value > -1)
                        GridViewDoc.SelectedItems.Add(Images[value]);
                }
                catch (OutOfMemoryException)
                { }
            }
        }

        /// <summary>
        /// Gets or sets the selected search documents.
        /// </summary>
        /// <value>The selected search documents.</value>
        public List<NetBay.Core.BusinessEntities.Document> SelectedSearchDocuments
        {
            get { return _selectedSearchDocuments; }
            set { _selectedSearchDocuments = value; }
        }


        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ListViewer" /> class.
        /// </summary>
        public ListViewer()
            : this(AppDisplayMode.None)
        { }

        /// <summary>
        /// Initializes a new instance of the <see cref="ListViewer" /> class.
        /// </summary>
        /// <param name="p_oDisplayMode">The p_o display mode.</param>
        /// <param name="p_oCurrentFolder">The p_o current folder.</param>
        /// <param name="p_oOrganization">The p_o organization.</param>
        /// <param name="p_oFolderType">Type of the p_o folder.</param>
        public ListViewer(AppDisplayMode p_oDisplayMode, Folder p_oCurrentFolder = null, NetBay.Core.BusinessEntities.Organization p_oOrganization = null, NetBay.Core.BusinessEntities.FolderType p_oFolderType = null)
            : base(null, p_oDisplayMode)
        {
            InitializeComponent();

            m_oCurrentFolderType = p_oFolderType;
            m_oCurrentOrganization = p_oOrganization;
            m_oFolder = p_oCurrentFolder;

            switch (CurrentDisplayMode)
            {
                case AppDisplayMode.Search:
                    DocumentToolbar.AppDisplayMode = AppCode.Enums.AppDisplayMode.Search;
                    DocumentContextMenu.AppDisplayMode = AppCode.Enums.AppDisplayMode.Search;
                    break;
                case AppDisplayMode.Import:
                    DocumentToolbar.AppDisplayMode = AppCode.Enums.AppDisplayMode.Import;
                    DocumentContextMenu.AppDisplayMode = AppCode.Enums.AppDisplayMode.Import;
                    break;
                case AppDisplayMode.Flow:
                    DocumentToolbar.AppDisplayMode = AppCode.Enums.AppDisplayMode.Flow;
                    DocumentContextMenu.AppDisplayMode = AppCode.Enums.AppDisplayMode.Flow;
                    break;
            }

            InitLabel();

            //Init Document toolbar
            DocumentToolbar.DocumentRibbonBarEvent += DocumentToolbar_DocumentRibbonBarEvent;
            DocumentToolbar.ViewMode = AppViewMode.List;
            DocumentToolbar.ManageToolbar();

            //Init document context menu
            RadContextMenu.SetContextMenu(GridViewDoc, DocumentContextMenu.ContextMenu);
            DocumentContextMenu.ViewMode = AppViewMode.List;
            DocumentContextMenu.ManageContextMenuItemState();
            DocumentContextMenu.DocumentContextMenuEvent += DocumentToolbar_DocumentRibbonBarEvent;

            GridViewDoc.AddHandler(GridViewCell.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnDoubleClick));
        }

        #endregion

        #region Private functions

        /// <summary>
        /// Protected method for raise the event 'ListDocumentUpdated'
        /// </summary>
        protected override void OnListDocumentUpdated()
        {
            ManageToolbarState();
            GetThumbnailList();
            base.OnListDocumentUpdated();
        }

        /// <summary>
        /// Gets the thumbnail list.
        /// </summary>
        public void GetThumbnailList()
        {
            if (!m_bReloadThumbnail)
            {
                m_bReloadThumbnail = true;
                return;
            }

            List<string> l_oListDocument = new List<string>();
            List<string> l_oOriginalDocument = new List<string>();

            try
            {
                if ((ListDocument != null) && (ListDocument.Count > 0))
                {
                    foreach (var l_oDoc in ListDocument)
                    {
                        l_oOriginalDocument.Add(Path.Combine(Path.Combine(ParameterStorage, l_oDoc.RelativePath), l_oDoc.ImageName));
                        l_oListDocument.Add(AddThumbnailExtension(Path.Combine(ParameterStorageThumbnail, l_oDoc.RelativePath, l_oDoc.ImageName)));
                    }

                    SplashScreenManager.Wait(this);

                    WCFServiceClient L_oWCFServiceClient = ServiceManager.GetRioWCFServiceClient();
                    L_oWCFServiceClient.GetImageFromFullPathCompleted += L_oWCFServiceClient_GetImageFromFullPathCompleted;
                    L_oWCFServiceClient.GetImageFromFullPathAsync(new ObservableCollection<string>(l_oListDocument), new ObservableCollection<string>(l_oOriginalDocument), ServiceManager.GetLicenseKey());
                }
                else
                {
                    ClearListViewer();
                    CursorNormal(this);
                }
            }
            catch (Exception ex)
            {
                CursorNormal(this);

                //Show error page
                ErrorPage errorPage = new ErrorPage(ex, "GetThumbnailList");
                errorPage.Show();
            }
        }

        /// <summary>
        /// Clears the list viewer.
        /// </summary>
        private void ClearListViewer()
        {
            Images = null;
            SelectedDocumentIndex = 0;
            SelectedSearchDocuments = null;
            CurrentSelectedDirectory = null;
            CurrentSelectedImage = null;
        }

        /// <summary>
        /// Handles the DocumentRibbonBarEvent event of the DocumentToolbar control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Rio.Framework.Pages.Events.DocumentRibbonBarEventArgs" /> instance containing the event data.</param>
        private void DocumentToolbar_DocumentRibbonBarEvent(object sender, Events.DocumentRibbonBarEventArgs args)
        {
            switch (args.DocumentRibbonBarMenuItem)
            {
                #region ScanImport
                case AppCode.Enums.DocumentRibbonBarMenuItems.Scan:
                    OnScanRequest();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Import:
                    OnImportRequest();
                    break;
                #endregion

                #region Selection
                case AppCode.Enums.DocumentRibbonBarMenuItems.SelectAll:
                    GridViewDoc.SelectAll();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SelectNone:
                    GridViewDoc.UnselectAll();
                    break;
                #endregion

                #region Display Mode
                case AppCode.Enums.DocumentRibbonBarMenuItems.DocumentMode:
                    DocumentContextMenu.ManageContextMenuItemState();
                    DocumentToolbar.ManageToolbar();
                    DocumentToolbar.HideMinimizedPopup();
                    OnActivateViewerMode();
                    break;

                case AppCode.Enums.DocumentRibbonBarMenuItems.ThumbnailsMode:
                    DocumentContextMenu.ManageContextMenuItemState();
                    DocumentToolbar.ManageToolbar();
                    DocumentToolbar.HideMinimizedPopup();
                    OnActivateThumbnailMode();
                    break;

                case AppCode.Enums.DocumentRibbonBarMenuItems.ListMode:
                    break;
                #endregion

                #region Fitting
                case AppCode.Enums.DocumentRibbonBarMenuItems.FitHeight:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.FitWidth:
                    break;

                #endregion

                #region Zoom
                case AppCode.Enums.DocumentRibbonBarMenuItems.ZoomIn:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ZoomOut:
                    break;
                #endregion

                #region Rotate
                case AppCode.Enums.DocumentRibbonBarMenuItems.RotateLeft:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.RotateRight:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SaveModifications:
                    SaveModificationOnThumbNails(Images);
                    break;

                #endregion

                #region Search
                case AppCode.Enums.DocumentRibbonBarMenuItems.SearchNext:
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.SearchPrevious:
                    break;
                #endregion

                #region Actions
                case AppCode.Enums.DocumentRibbonBarMenuItems.SendEmail:
                    SendMail(GetListDocumentFromSelectedThumbnails());
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Delete:
                    DeleteItems();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.MergePDF:
                    OnMergePDF();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Download:
                    SaveDocumentsLocally(GridViewDoc.SelectedItems);
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Print:
                    PrintIndexedDocuments(GridViewDoc.SelectedItems);
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.AddDocument:
                    OnAddDocumentEvent();
                    break;
                case DocumentRibbonBarMenuItems.FolderLink:
                    ShowFolderLinkWindow();
                    break;
                #endregion

                #region Edit
                case AppCode.Enums.DocumentRibbonBarMenuItems.Cut:
                    OnCutClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Copy:
                    OnCopyClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.Paste:
                    OnPasteClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.CheckOut:
                    OnCheckOutClick();
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.CheckIn:
                    OnCheckInClick();
                    break;
                #endregion

                #region Workflow
                case AppCode.Enums.DocumentRibbonBarMenuItems.Ventilate:
                    VentilateDocuments(GridViewDoc.SelectedItems);
                    break;
                #endregion

                #region Outlook
                case AppCode.Enums.DocumentRibbonBarMenuItems.OpenDirectory:
                    SaveModificationOnImage(ClickEvent.OpenDirectory);
                    break;
                case AppCode.Enums.DocumentRibbonBarMenuItems.ReturnDirectory:
                    SaveModificationOnImage(ClickEvent.ReturnDirectory);
                    break;
                #endregion

            }
        }

        private void OnMergePDF()
        {
            RefreshThumbnails += ListViewer_RefreshThumbnails;
            SetActuallyRankingList();
            if (SelectedImages != null && SelectedImages.Count > 0)
            {
                SaveModificationOnThumbNails(SelectedImages, true);
            }
            else
            {
                SaveModificationOnThumbNails(GridViewDoc.SelectedItems, true);
            }
        }

        /// <summary>
        /// Configures the columns binding.
        /// </summary>
        private void ConfigureColumnsBinding()
        {
            ((Telerik.Windows.Controls.GridViewImageColumn)GridViewDoc.Columns["TypeHeader"]).DataMemberBinding.ConverterParameter = CurrentDisplayMode == AppDisplayMode.Import || CurrentDisplayMode == AppDisplayMode.AddDocument ? "Import" : String.Empty;

            if (CurrentDisplayMode == AppDisplayMode.Import || CurrentDisplayMode == AppDisplayMode.AddDocument)
            {
                ((Telerik.Windows.Controls.GridViewImageColumn)GridViewDoc.Columns["TypeHeader"]).DataMemberBinding.Path = new PropertyPath("Name");
                ((Telerik.Windows.Controls.GridViewDataColumn)GridViewDoc.Columns["NameHeader"]).DataMemberBinding.Path = new PropertyPath("Name");
                ((Telerik.Windows.Controls.GridViewDataColumn)GridViewDoc.Columns["NameHeader"]).DataMemberBinding.Converter = Resources["PathFileToFileNameConverterWithoutExtension"] as PathFileToFileNameConverterWithoutExtension;
            }
            else
            {
                ((Telerik.Windows.Controls.GridViewImageColumn)GridViewDoc.Columns["TypeHeader"]).DataMemberBinding.Path = new PropertyPath("OriginalName");
                ((Telerik.Windows.Controls.GridViewDataColumn)GridViewDoc.Columns["NameHeader"]).DataMemberBinding.Path = new PropertyPath("OriginalName");
                ((Telerik.Windows.Controls.GridViewDataColumn)GridViewDoc.Columns["NameHeader"]).DataMemberBinding.Converter = Resources["PathFileToFileNameConverter"] as PathFileToFileNameConverter;
            }
        }

        /// <summary>
        /// Called when a double-click on a row
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Telerik.Windows.RadRoutedEventArgs"/> instance containing the event data.</param>
        private void OnDoubleClick(object sender, RadRoutedEventArgs e)
        {
            if (e.Source is GridViewCell)
            {
                switch (CurrentDisplayMode)
                {
                    case AppDisplayMode.AddDocument:
                    case AppDisplayMode.Import:
                        CurrentSelectedImage = ((GridViewCell)e.Source).DataContext as ImageRio;

                        if (CurrentSelectedImage != null)
                        {
                            //Selected thumbnail is not a directory
                            if (!CurrentSelectedImage.isDirectory)
                            {
                                GetFileNameSelected = Utils.RemoveExtension(CurrentSelectedImage.Name);
                                SaveModificationOnImage(ClickEvent.ListBoxItemChange);
                            }
                            else if (CurrentSelectedImage.isDirectory)
                            {
                                //Show document inside the current selected directory
                                CurrentSelectedDirectory = CurrentSelectedImage.Name;
                                SaveModificationOnImage(ClickEvent.OpenDirectory);
                            }
                        }

                        ManageToolbarState();

                        break;
                    case AppDisplayMode.Search:
                    case AppDisplayMode.Flow:
                        ImageRioSearch selectedImageRioSearch = ((GridViewCell)e.Source).DataContext as ImageRioSearch;

                        if (selectedImageRioSearch != null)
                        {
                            SaveModificationOnImage(ClickEvent.ListBoxItemChange, GetListDocumentFromSelectedThumbnails());
                        }
                        break;
                    default:
                        break;
                }
            }
        }

        /// <summary>
        /// Return a list of selected documents
        /// </summary>
        /// <returns></returns>
        private new List<NetBay.Core.BusinessEntities.Document> GetListDocumentFromSelectedThumbnails()
        {
            List<NetBay.Core.BusinessEntities.Document> L_oListDocument = new List<NetBay.Core.BusinessEntities.Document>();

            if ((GridViewDoc.SelectedItems != null) && (GridViewDoc.SelectedItems.Count > 0) && ListDocument != null)
            {
                if (CurrentDisplayMode != AppDisplayMode.Search)
                {
                    //In this mode we check image path
                    string L_szImageSearchName;
                    foreach (ImageRioSearch imgSearch in GridViewDoc.SelectedItems)
                    {
                        L_szImageSearchName = imgSearch.ImageName;

                        foreach (NetBay.Core.BusinessEntities.Document doc in ListDocument)
                        {
                            if (L_szImageSearchName.Equals(doc.ImageName))
                            {
                                L_oListDocument.Add(doc);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    //In search mode we check the unique identifier
                    foreach (ImageRioSearch imgSearch in GridViewDoc.SelectedItems)
                    {
                        long imageIdentifier = imgSearch.Identifier;
                        foreach (NetBay.Core.BusinessEntities.Document doc in ListDocument)
                        {
                            if (imageIdentifier == doc.Identifier)
                            {
                                L_oListDocument.Add(doc);
                                break;
                            }
                        }
                    }

                }
            }

            return L_oListDocument;
        }

        /// <summary>
        /// Inits the label.
        /// </summary>
        public override sealed void InitLabel()
        {
            base.InitLabel();
            /*
             * Label for MessageWindow
             */

            LabelMergePdfQuestion = Rio.Framework.Localisation.Resx.GetLabel(ResxCommon.MERGE_PDF_QUESTION);
            LabelMergePDFFormatFileError = Rio.Framework.Localisation.Resx.GetLabel(ResxCommon.MERGEPDF_FORMATFILE_ERROR);
            LabelDeleteThumbnail = Rio.Framework.Localisation.Resx.GetLabel(ResxCommon.DELETE_THUMBNAIL_CONFIRMATION);
            LabelSaveModificationImage = Rio.Framework.Localisation.Resx.GetLabel(ResxListVignetteSearch.SAVE_MODIFICATION_CONFIRMATION);

            /*
             * GridView Headers
             */
            GridViewDoc.Columns["TypeHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.TYPE_HEADER);
            GridViewDoc.Columns["NameHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.NAME_HEADER);
            GridViewDoc.Columns["NumberPagesHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.NUMBER_PAGES_HEADER);
            //GridViewDoc.Columns["AuthorHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.AUTHOR_HEADER);
            GridViewDoc.Columns["CreationDateHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.CREATION_DATE_HEADER);
            GridViewDoc.Columns["DimensionHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.DIMENSION_HEADER);
            //GridViewDoc.Columns["LastModificationAuthorHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.LAST_MODIFICATION_AUTHOR_HEADER);
            GridViewDoc.Columns["LastModificationDateHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.LAST_MODIFICATION_DATE_HEADER);
            GridViewDoc.Columns["ResolutionHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.RESOLUTION_HEADER);
            GridViewDoc.Columns["SizeHeader"].Header = Rio.Framework.Localisation.Resx.GetLabel(ResxListViewer.SIZE_HEADER);

            LabelRotateUnsupportedFile = Resx.GetLabel(ResxListVignetteSearch.ROTATE_UNSUPPORTED_FILE);
        }

        /// <summary>
        /// Selects the images.
        /// </summary>
        public override void UpdateSelectImages()
        {
            if (SelectedImages != null)
            {
                List<ImageRio> selectedImageBeforeClear = new List<ImageRio>(SelectedImages);
                GridViewDoc.SelectedItems.Clear();

                foreach (var item in selectedImageBeforeClear)
                {
                    GridViewDoc.SelectedItems.Add(item);
                }

                _selectedImages = selectedImageBeforeClear;
            }
        }

        /// <summary>
        /// Handles the ImportedDocumentMergedFailed event of the ListViewer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ListViewer_ImportedDocumentMergedFailed(object sender, EventArgs e)
        {
            RefreshItems();
        }

        /// <summary>
        /// Lists the viewer_ imported document refreshed.
        /// </summary>
        /// <param name="p_oImageRioCollection">The p_o image rio collection.</param>
        private void ListViewer_ImportedDocumentRefreshed(IList p_oImageRioCollection)
        {
            Images = ManageDocumentListRank(p_oImageRioCollection as ObservableCollection<ImageRio>);

            ImportedDocumentRefreshed -= ListViewer_ImportedDocumentRefreshed;

            CursorNormal(this);
        }

        public void RefreshImages(IList p_oImageRioCollection)
        {
            Images = ManageDocumentListRank(p_oImageRioCollection as ObservableCollection<ImageRio>);
        }

        /// <summary>
        /// Deletes the items.
        /// </summary>
        private void DeleteItems()
        {
            if (CurrentDisplayMode == AppDisplayMode.Import || CurrentDisplayMode == AppDisplayMode.AddDocument)
            {
                ImportedDocumentDeleted += ListViewer_ImportedDocumentDeleted;
                DeleteImportedDocuments(GridViewDoc.SelectedItems.Cast<ImageRio>().ToList());
            }
            else
            {
                if (SelectedSearchDocuments !=null)
                    RemoveOrDeleteSelectedDocuments(SelectedSearchDocuments.Select(item => item.Identifier).ToList(), OnDeleteDocumentQueryCallback);
            }
        }

        /// <summary>
        /// Lists the viewer_ imported document deleted.
        /// </summary>
        /// <param name="p_oImageRioDeleted">The p_o image rio deleted.</param>
        private void ListViewer_ImportedDocumentDeleted(ImageRio p_oImageRioDeleted)
        {
            ImportedDocumentDeleted -= ListViewer_ImportedDocumentDeleted;
            Images.Remove(p_oImageRioDeleted);
            m_oItemsSource.Remove(p_oImageRioDeleted);
        }

        /// <summary>
        /// Handles the GetImageFromFullPathCompleted event of the L_oWCFServiceClient control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rio.Framework.WCFService.RioWcfServices.GetImageFromFullPathCompletedEventArgs" /> instance containing the event data.</param>
        private void L_oWCFServiceClient_GetImageFromFullPathCompleted(object sender, GetImageFromFullPathCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                List<ImageRio> l_oImageRioList = new List<ImageRio>(e.Result);
                NetBay.Core.BusinessEntities.Document l_szImageRioDoc;

                Images = new ObservableCollection<ImageRioSearch>();
                int identifierCounter = 0;
                foreach (ImageRio ImgRio in l_oImageRioList)
                {
                    l_szImageRioDoc = ListDocument.Where(item => System.IO.Path.GetFileName(AddThumbnailExtension(item.ImageName)).Equals(ImgRio.Name)).FirstOrDefault();
                    if (ListDocument.Count > identifierCounter)
                    {
                        long DocumentIdentifier = ListDocument[identifierCounter].Identifier;

                        if (l_szImageRioDoc != null)
                        {
                            ImageRioSearch L_oImgRioSearch = new ImageRioSearch(DocumentIdentifier, ImgRio.Name, ImgRio.Img, ImgRio.ImageSize, l_szImageRioDoc.OriginalNameFile, l_szImageRioDoc.ImageName, l_szImageRioDoc.RelativePath, ImgRio.NumberPages)
                                                                 {
                                                                     CreationDate = ImgRio.CreationDate,
                                                                     LastModificationDate = ImgRio.LastModificationDate,
                                                                     ImageSize = ImgRio.ImageSize,
                                                                     Dimension = ImgRio.Dimension,
                                                                     Resolution = ImgRio.Resolution,
                                                                     Author = ImgRio.Author,
                                                                     LastModificationAuthor = ImgRio.LastModificationAuthor
                                                                 };

                            if (m_oFolder != null && m_oFolder.FullTextDocList != null && m_oFolder.FullTextDocList.Any(f => f.Equals(System.IO.Path.Combine(l_szImageRioDoc.RelativePath, l_szImageRioDoc.ImageName))))
                            {
                                L_oImgRioSearch.IsFullSearch = true;
                            }
                            Images.Add(L_oImgRioSearch);
                        }
                    }
                    identifierCounter++;
                }

                OnPropertyChanged("Images");

                // Search the selected item
                ImageRioSearch l_oImageRioSearchSelected = new ImageRioSearch();
                if (GridViewDoc.SelectedItem != null)
                {
                    l_oImageRioSearchSelected = (ImageRioSearch)GridViewDoc.SelectedItem;
                }
                int l_iLoop = -1;
                bool l_bTouched = false;
                foreach (ImageRioSearch l_oItem in Images)
                {
                    l_iLoop++;
                    if (l_oItem.Identifier == l_oImageRioSearchSelected.Identifier)
                    {
                        l_bTouched = true;
                        break;
                    }
                }
                if (l_bTouched)
                {
                    GridViewDoc.SelectedItem = Images[l_iLoop];
                }
                else
                {
                    if (Images != null && Images.Count > 0)
                        GridViewDoc.SelectedItem = Images[0];
                }

                // Set copied files theme
                foreach (var id in GlobalWebContext.CopyPasteManager.Documents)
                {
                    try
                    {
                        GridViewDoc.Items.Cast<ImageRioSearch>().Where(t => t.Identifier == id).FirstOrDefault().IsCutedOrCopied = true;
                    }
                    catch { }
                }

                CursorNormal(this);
            }
        }

        /// <summary>
        /// Called when [delete document query callback].
        /// </summary>
        /// <param name="result">The result.</param>
        private void OnDeleteDocumentQueryCallback(LoadOperation<NetBay.Core.BusinessEntities.ReturnObject> result)
        {
            if (result.Error != null)
            {
                //Logger.Write("EXCEPTION : " + Environment.NewLine + result.Error, Logger.Level.Error);
            }
            else
            {
                // Remove selectedFileName
                List<ImageRioSearch> L_oListImageDeleted = new List<ImageRioSearch>();

                if (GridViewDoc.SelectedItems != null && GridViewDoc.SelectedItems.Count > 0)
                {
                    foreach (ImageRioSearch itemVignettte in GridViewDoc.SelectedItems)
                    {
                        L_oListImageDeleted.Add(itemVignettte);
                    }
                }

                List<NetBay.Core.BusinessEntities.Document> L_oListDocumentDeleted = GetListDocumentFromSelectedThumbnails();

                foreach (ImageRioSearch item in L_oListImageDeleted)
                {
                    ObservableCollection<ImageRioSearch> src = (ObservableCollection<ImageRioSearch>)GridViewDoc.ItemsSource;
                    src.Remove(item);

                    if (ModifyRotateList.ContainsKey(System.IO.Path.GetFileNameWithoutExtension(item.Name)))
                    {
                        ModifyRotateList.Remove(System.IO.Path.GetFileNameWithoutExtension(item.Name));
                    }
                }

                OnItemsDeletedToRemove(L_oListDocumentDeleted);

                //Stop SplashScreen after delete
                CursorNormal(this);
                SplashScreenManager.Stop(this);
            }
        }

        /// <summary>
        /// Handles the RefreshThumbnails event of the ListViewer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ListViewer_RefreshThumbnails(object sender, EventArgs e)
        {
            RefreshThumbnails -= ListViewer_RefreshThumbnails;

            RefreshItems();
        }

        /// <summary>
        /// Handles the SelectionChanged event of the GridViewDoc control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Windows.Controls.SelectionChangeEventArgs"/> instance containing the event data.</param>
        private void GridViewDoc_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
        {

            if (GridViewDoc.SelectedItem != null)
            {
                SelectedDocumentIndex = GridViewDoc.Items.IndexOf(GridViewDoc.SelectedItem);
            }
            else
            {
                SelectedDocumentIndex = 0;
            }


            if (CurrentDisplayMode == AppDisplayMode.Import || CurrentDisplayMode == AppDisplayMode.AddDocument)
            {
                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);
            }

            if (GridViewDoc.SelectedItems.Count == 1)
            {
                if (CurrentDisplayMode != AppDisplayMode.Import || CurrentDisplayMode == AppDisplayMode.AddDocument)
                {
                    DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.Download, true);
                    DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.Download, true);
                }

                CurrentSelectedImage = GridViewDoc.SelectedItem as ImageRio;


                if ((CurrentSelectedImage != null && CurrentDisplayMode == AppDisplayMode.Import && System.IO.Path.GetExtension(System.IO.Path.GetFileNameWithoutExtension(CurrentSelectedImage.Name)) == ".pdf"))
                {
                    DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, false);
                    DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, false);
                }
            }
            else
            {
                if ((CurrentDisplayMode != AppDisplayMode.Import || CurrentDisplayMode == AppDisplayMode.AddDocument) && DocumentToolbar.CanDownload)
                {
                    DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.Download, false);
                    DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.Download, false);
                }
            }


            if (CurrentDisplayMode == AppDisplayMode.Import || CurrentDisplayMode == AppDisplayMode.AddDocument)
            {
                List<string> m_oListItemSelectedFileName = new List<string>();
                _selectedImages = new List<ImageRio>();
                if (GridViewDoc.SelectedItems.Count > 0)
                {
                    foreach (ImageRio item in GridViewDoc.SelectedItems)
                    {
                        m_oListItemSelectedFileName.Add(Utils.RemoveExtension(item.Name));
                        _selectedImages.Add(item);
                    }
                }

                OnItemsSelected(m_oListItemSelectedFileName);
            }
            else if (CurrentDisplayMode == AppDisplayMode.Search || CurrentDisplayMode == AppDisplayMode.Flow)
            {
                SelectedSearchDocuments = new List<NetBay.Core.BusinessEntities.Document>();

                foreach (ImageRioSearch imgSearch in GridViewDoc.SelectedItems)
                {
                    string L_szImageSearchName = imgSearch.ImageName;

                    foreach (NetBay.Core.BusinessEntities.Document doc in ListDocument)
                    {
                        if (L_szImageSearchName.Equals(doc.ImageName))
                        {
                            SelectedSearchDocuments.Add(doc);
                            break;
                        }
                    }
                }
                if (SelectedSearchDocuments != null && SelectedSearchDocuments.Count > 0)
                {
                    OnItemsSelected(SelectedSearchDocuments);
                }
            }

            ManageToolbarState();
        }

        /// <summary>
        /// Handles the KeyUp event of the GridViewDoc control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
        private void GridViewDoc_KeyUp(object sender, KeyEventArgs e)
        {
            //SUPPR
            if (e.Key == Key.Delete && (DocumentToolbar.CanDelete | CurrentDisplayMode == AppDisplayMode.Import))
            {
                DeleteItems();
                return;
            }

            //Ctrl + X
            if (e.Key == Key.X && DocumentToolbar.CanDelete && CurrentDisplayMode == AppDisplayMode.Search)
            {
                if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    OnCutClick();
                    return;
                }
            }

            //Ctrl + C
            if (e.Key == Key.C && DocumentToolbar.CanDownload && CurrentDisplayMode == AppDisplayMode.Search)
            {
                if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    OnCopyClick();
                    return;
                }
            }

            //Ctrl + V
            if (e.Key == Key.V && DocumentToolbar.CanModify && CurrentDisplayMode == AppDisplayMode.Search)
            {
                if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
                {
                    OnPasteClick();
                    return;
                }
            }
        }

        /// <summary>
        /// Handles the Loaded event of the GridViewDoc control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void GridViewDoc_Loaded(object sender, RoutedEventArgs e)
        {
            GridViewDoc.Focus();
        }

        /// <summary>
        /// Handles the Loaded event of the ListDisplay control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void ListDisplay_Loaded(object sender, RoutedEventArgs e)
        {
            //Enable Drag and Drop
            RowReorderBehavior.SetIsEnabled(GridViewDoc, true, CurrentDisplayMode);

            if (GridViewDoc.ItemsSource == null)
            {
                ConfigureColumnsBinding();
            }

            if (CurrentDisplayMode == AppDisplayMode.Import)
            {
                ImportedDocumentMergedFailed += ListViewer_ImportedDocumentMergedFailed;
            }


            FireOnInitialisationCompleted();
        }


        #endregion

        #region Public functions

        /// <summary>
        /// Manage state of toolbar icons following listbox thumbnails selection
        /// </summary>
        public sealed override void ManageToolbarState()
        {
            //Manage visibility of other actions
            if (CurrentDisplayMode == AppDisplayMode.Import)
            {
                //Manage visibility of other actions
                if (SelectedImages != null)
                {
                    DocumentToolbar.SelectedDocumentCount = SelectedImages.Count;
                    DocumentContextMenu.SelectedDocumentCount = SelectedImages.Count;

                    if (SelectedImages.Count == 1)
                    {

                        if (SelectedImages[0].isDirectory)
                        {
                            DocumentContextMenu.ChangeAppDisplayMode(AppDisplayMode.ImportDirectory);
                            DocumentToolbar.ChangeAppDisplayMode(AppDisplayMode.ImportDirectory);
                        }
                        else
                        {
                            DocumentContextMenu.ChangeAppDisplayMode(AppDisplayMode.Import);
                            DocumentToolbar.ChangeAppDisplayMode(AppDisplayMode.Import);
                        }

                        //Set PDF visibility
                        if ((Path.GetExtension(Path.GetFileNameWithoutExtension(SelectedImages[0].Name)) == ".pdf"))
                        {
                            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, false);
                            DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, false);

                            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, true);
                            DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, true);
                        }
                        else
                        {
                            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);
                            DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);

                            DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
                            DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
                        }
                    }
                    else if (SelectedImages.Count > 1)
                    {
                        //Get a list of Directories and images from selection
                        var l_oListDirectories = (from img in SelectedImages where img.isDirectory select img).ToList<ImageRio>();
                        var l_oListImages = (from img in SelectedImages where !img.isDirectory select img).ToList<ImageRio>();

                        if (l_oListDirectories.Count > 0 && l_oListImages.Count > 0)
                        {
                            DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                            DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                        }
                        else
                        {
                            DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.Import);
                            DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.Import);
                        }

                        //Set PDF visibility
                        DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);
                        DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.MergePDF, true);
                        DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
                        DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SplitPDF, false);
                    }
                    else
                    {
                        //set all menus disabled
                        DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                        DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                    }
                }
                else
                {
                    //set all menus disabled
                    DocumentContextMenu.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                    DocumentToolbar.ChangeAppDisplayMode(AppCode.Enums.AppDisplayMode.None);
                }

                //Return directory is activated only if the a directory is selected
                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.ReturnDirectory, !string.IsNullOrEmpty(CurrentSelectedDirectory), true);
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.ReturnDirectory, !string.IsNullOrEmpty(CurrentSelectedDirectory), true);

                //Manage save modification
                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.SaveModifications, SaveModificationEnabled);
                DocumentContextMenu.SetAvailability(DocumentRibbonBarMenuItems.SaveModifications, SaveModificationEnabled);

                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.CheckOut, false);
                DocumentToolbar.SetAvailability(DocumentRibbonBarMenuItems.CheckIn, false);

                OnToolbarStateHasChanged();
            }
            else
            {
                if(SelectedSearchDocuments !=null && SelectedSearchDocuments.Count> 0)
                {
                    DocumentToolbar.SelectedDocumentCount = SelectedSearchDocuments.Count;
                    DocumentContextMenu.SelectedDocumentCount = SelectedSearchDocuments.Count;

                    DocumentContextMenu.ChangeAppDisplayMode(AppDisplayMode.Search);
                    DocumentToolbar.ChangeAppDisplayMode(AppDisplayMode.Search);
                }
                else
                {
                    DocumentContextMenu.ChangeAppDisplayMode(AppDisplayMode.SearchNone);
                    DocumentToolbar.ChangeAppDisplayMode(AppDisplayMode.SearchNone);
                }
            }
        }

        /// <summary>
        /// Return a ImageRioSearch list from the selected thumbnails
        /// </summary>
        /// <returns></returns>
        public override List<T> GetSelectedImage<T>()
        {
            List<T> resultList = new List<T>();
            if (GridViewDoc != null && GridViewDoc.SelectedItems.Count > 0)
            {
                foreach (T imgSearch in GridViewDoc.SelectedItems)
                {
                    resultList.Add(imgSearch);
                }
            }
            return resultList;
        }

        /// <summary>
        /// Sets the selected image search.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="images">The images.</param>
        public override void SetSelectedImage<T>(List<T> images)
        {
            if (images != null && images.Count > 0)
            {
                GridViewDoc.SelectedItems.Clear();
                foreach (T img in images)
                {
                    GridViewDoc.SelectedItems.Add(img);
                }
            }
        }

        /// <summary>
        /// Refreshes the items.
        /// </summary>
        public void RefreshItems(bool ShowWaitMessage = true)
        {
            if (ShowWaitMessage)
                CursorWait(this);

            ImportedDocumentRefreshed += ListViewer_ImportedDocumentRefreshed;

            RefreshImportedDocuments();
        }

        /// <summary>
        /// Changes the consultation mode
        /// </summary>
        /// <param name="organization">Organization</param>
        /// <param name="folderType">Folder type</param>
        /// <param name="modeToApply">Mode to apply</param>
        /// <param name="isVersioningActivated">if set to <c>true</c> [is versioning activated].</param>
        public override void ChangeConsultationMode(NetBay.Core.BusinessEntities.Organization organization, NetBay.Core.BusinessEntities.FolderType folderType, ConsultationModeType modeToApply, bool isVersioningActivated = false)
        {
            //Apply rights before change the mode
            DocumentToolbar.SetUserPriviledges(folderType, organization);
            DocumentContextMenu.SetUserPriviledges(folderType, organization);

            DocumentToolbar.ConsultationMode = modeToApply;
            DocumentContextMenu.ConsultationMode = modeToApply;
            this.ConsultationMode = modeToApply;

            DocumentToolbar.IsVersioningEnabled = isVersioningActivated;
            DocumentContextMenu.IsVersioningEnabled = isVersioningActivated;
        }

        /// <summary>
        /// Sets the actually ranking list.
        /// </summary>
        public override void SetActuallyRankingList()
        {
            var L_oActuallyRankedList = from L_oImageRio in (ObservableCollection<ImageRio>)GridViewDoc.ItemsSource
                                        select Utils.RemoveExtension(L_oImageRio.Name);

            RankedListFromViewer = new List<string>(L_oActuallyRankedList);
        }

        #endregion

        #region Copy-Cut-Paste

        /// <summary>
        /// Return an identifier list from the selected thumbnails
        /// </summary>
        /// <returns>Lsit of identifiers.</returns>
        protected override List<long> GetListIdentifierToCopy()
        {
            List<long> resultList = new List<long>();

            //Reset all 
            foreach (var id in GlobalWebContext.CopyPasteManager.Documents)
            {
                var item = GridViewDoc.Items.Cast<ImageRioSearch>().Where(t => t.Identifier == id).FirstOrDefault();
                if (item != null)
                {
                    item.IsCutedOrCopied = false;
                }
            }

            if (GridViewDoc != null && GridViewDoc.SelectedItems.Count > 0)
            {
                foreach (ImageRioSearch imgSearch in GridViewDoc.SelectedItems)
                {
                    resultList.Add(imgSearch.Identifier);
                    imgSearch.IsCutedOrCopied = true; //Set visual state
                }
            }
            return resultList;
        }

        /// <summary>
        /// Updates the copy paste selection.
        /// </summary>
        public override void UpdateCopyPasteSelection()
        {
            if ((GridViewDoc.Items != null) && (GridViewDoc.Items.Count > 0) && (ListDocument != null))
            {
                foreach (ImageRioSearch imgSearch in GridViewDoc.Items)
                {
                    var item = GlobalWebContext.CopyPasteManager.Documents.SingleOrDefault(t => t == imgSearch.Identifier);
                    if (item == 0)
                    {
                        imgSearch.IsCutedOrCopied = false;
                    }
                    else
                    {
                        imgSearch.IsCutedOrCopied = true;
                    }
                }
            }
        }

        #endregion
    }
}